import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class Producer {
    private Message message;
    private String num;
    private static final int NUM_COUNT = 1000000;
    private static final BlockingQueue<Long> queue = new LinkedBlockingQueue<>();
    public static void main(String[] args) {
        ExecutorService socketThread = Executors.newFixedThreadPool(2);
        Random random = new Random();
        for (int i = 0; i < NUM_COUNT; i++) {
            long num = 2000000000 + random.nextInt(2000000000);
            num = Math.abs(num);
            try {
                queue.put(num);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        while (true) {
            if (queue.isEmpty()) {
                break;
            }
            String num;
            try {
                long n = queue.take();
                num = String.valueOf(n);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Message msg = new Message("produce",num);
            Runnable runnable = () -> {
                try {
                    String host = "localhost";
                    int port = 8888;

                    Socket socket = new Socket(host, port);
                    OutputStream out = socket.getOutputStream();
                    System.out.println("Send the msg to localhost! port:8888"+msg);
                    ObjectOutputStream oos = new ObjectOutputStream(out);
                    oos.writeObject(msg);
                    socket.shutdownOutput();

                    InputStream in = socket.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len;

                    while ((len = in.read(buffer)) != -1) {

                    }
                    in.close();
                    out.close();
                    socket.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            };
            socketThread.submit(runnable);
        }
    }
}
